#include "../include/RabbitMQ.h"
#include "../include/Backup.h"
#include <nlohmann/json.hpp>

using json = nlohmann::json;

void RabbitMQ::push(string exchange, string routingKey, string content) {
    string host = "127.0.0.1";    
    int port = 5672;    
    string username = "guest";
    string password = "guest";
    string vhost = "/";

    // 创建Channel
    AmqpClient::Channel::ptr_t channel = AmqpClient::Channel::Create(host, port, username, password, vhost);

    // 构建消息
    AmqpClient::BasicMessage::ptr_t message = AmqpClient::BasicMessage::Create(content);

    // 发布消息
    // string exchange = "my.direct";
    // string routingKey = "key1";
    channel->BasicPublish(exchange, routingKey, message);
}

void RabbitMQ::pop(string q) {
    string uri = "amqp://guest:guest@localhost:5672/%2f";
    AmqpClient::Channel::ptr_t channel = AmqpClient::Channel::CreateFromUri(uri);

    AmqpClient::Envelope::ptr_t envelope;
    // const std::string& q = "q1";

    channel->BasicConsume(q);

    for(;;) {
        Envelope::ptr_t envelope = channel->BasicConsumeMessage();
        // 打印消息
        if (envelope && envelope->Message()) {
            std::cout << "[q1]:" << envelope->Message()->Body() << "\n";

            json j = json::parse(envelope->Message()->Body());
            // cout << "[json]: " << j << endl;
            cout << "[json]: " << j.dump(2) << endl;

            string srcpath = j["srcpath"];
            string savepath = j["savepath"];

            cout << "[srcpath]: " << srcpath << endl;
            cout << "[savepath]: " << savepath << endl;
            
            if (Backup::backupByFile(srcpath, savepath)) {
                cout << "backup success." << endl << endl;
            }
        }
    }
}
